#include "CSVExporterDialog.h"
#include "ui_CSVExporterDialog.h"
#include "../CSVExporter.h"
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <QMessageBox>
#include <MMM/Motion/Plugin/KinematicPlugin/KinematicSensor.h>
#include <MMM/Motion/Plugin/KinematicPlugin/KinematicSensorMeasurement.h>
#include <MMM/Motion/Plugin/ModelPosePlugin/ModelPoseSensor.h>

using namespace MMM;

CSVExporterDialog::CSVExporterDialog(const std::string &exportDirectoryPath, MMM::MotionList motions, QWidget* parent) :
    QDialog(parent),
    ui(new Ui::CSVExporterDialog),
    motions(motions),
    exportDirectoryPath(exportDirectoryPath)
{
    ui->setupUi(this);

    std::tuple<float, float> timestepTuple = MMM::Motion::calculateMinMaxTimesteps(motions);
    float minTimestep = std::get<0>(timestepTuple);
    float maxTimestep = std::get<1>(timestepTuple);

    ui->MinTimestepSpin->setMinimum(minTimestep);
    ui->MaxTimestepSpin->setValue(minTimestep);
    ui->MinTimestepSpin->setMaximum(maxTimestep);
    ui->MaxTimestepSpin->setMinimum(minTimestep);
    ui->MaxTimestepSpin->setValue(maxTimestep);
    ui->MaxTimestepSpin->setMaximum(maxTimestep);

    connect(ui->ExportButton, SIGNAL(clicked()), this, SLOT(exportMotions()));
    connect(ui->CancelButton, SIGNAL(clicked()), this, SLOT(close()));
}

void CSVExporterDialog::exportMotions() {
    float minTimestep = ui->MinTimestepSpin->value();
    float maxTimestep = ui->MaxTimestepSpin->value();
    int framesPerSecond = ui->FPSSpin->value();

    if (minTimestep > maxTimestep) {
        QMessageBox* msgBox = new QMessageBox(this);
        std::string error_message = "Minimum timestep should be smaller than maximum timestep!";
        msgBox->setText(QString::fromStdString(error_message));
        MMM_INFO << error_message << std::endl;
        msgBox->exec();
    }

    CSVExportPlugin* exporter = new CSVExportPlugin();
    exporter->exportCSV(motions, exportDirectoryPath, ui->boxLocTraj->isChecked(), ui->handTraj->isChecked(), minTimestep, maxTimestep, framesPerSecond);

    close();
}

CSVExporterDialog::~CSVExporterDialog() {
    delete ui;
}
